package com.esun.gateway.service.impl;

import com.esun.common.utils.JDBCUtils;
import com.esun.gateway.bean.Param;
import com.esun.gateway.bean.Result;
import com.esun.gateway.service.GatewayService;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("gatewayService")
public class GatewayServiceImpl implements GatewayService {

    @Override
    public Integer checkRouterType(Integer routerId) throws SQLException {
        //获取mysql连接
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            connect = JDBCUtils.getConnection();
            String sql = "select type from t_router where id = " + routerId;
            preparedStatement = connect.prepareStatement(sql);
            rs = preparedStatement.executeQuery();
            rs.next();
            return Integer.parseInt(rs.getString("type"));
        } finally {
            connect.close();
        }
    }

    @Override
    public Result update(Param param) {
        Connection connect = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Result result = new Result();
        String query = "";
        try {
            //1.通过t_router_do表获取该接口执行的sql(或视图/存储过程)
            connect = JDBCUtils.getConnection();
            String sql = "select do_content as content from t_router_do where router_id = ?";
            ps = connect.prepareStatement(sql);
            ps.setInt(1, param.getRouterId());
            rs = ps.executeQuery();
            rs.next();
            query += rs.getString("content");
            //2. 检查参数数量是否匹配
            System.out.println("传参个数： "  + param.getData().size() );
            System.out.println("需要参数个数： "  + this.countChar(query , '?'));
            if(param.getData().size() != this.countChar(query , '?')){
                System.out.println("触发节点A-1");
                result.setSuccess(false);
                result.setMessage("参数不匹配");
                return result;
            }
            //3. 注入参数
            ps = connect.prepareStatement(query);
            this.replaceParam(ps, param);
            //4. 执行sql
            int i = ps.executeUpdate();
            if (i < 0) {
                result.setMessage("操作失败");
                result.setSuccess(false);
                return result;
            }
            result.setMessage("操作成功, 操作了" + i + "条记录");
            result.setSuccess(true);
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
            result.setMessage("操作失败");
            result.setSuccess(false);
            return result;
        } finally {
            JDBCUtils.close(rs, ps, connect);
        }
    }


    @Override
    public Result query(Param param) {
        Connection connect = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Result result = new Result();
        List<Object> dataList = new ArrayList<>();
        String query = "";
        try {
            //1.通过t_router_do表获取该接口执行的sql(或视图/存储过程)
            connect = JDBCUtils.getConnection();
            String sql = "select do_content as content from t_router_do where router_id = ?";
            ps = connect.prepareStatement(sql);
            ps.setInt(1, param.getRouterId());
            rs = ps.executeQuery();
            rs.next();
            query += rs.getString("content");
            //2. 检查参数数量是否匹配
            if(param.getData() == null){
                if(this.countChar(query , '?') != 0){
                    result.setSuccess(false);
                    result.setMessage("参数不匹配");
                    return result;
                }
            }else if(param.getData().size() != this.countChar(query , '?')){
                result.setSuccess(false);
                result.setMessage("参数不匹配");
                return result;
            }
            //3. 注入参数
            ps = connect.prepareStatement(query);
            this.replaceParam(ps, param);
            //执行sql
            rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
            int columnCount = md.getColumnCount();   //获得列数
            while (rs.next()) {
                Map<String,Object> rowData = new HashMap<String,Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                dataList.add(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("加载列表失败");
            return result;
        } finally {
            JDBCUtils.close(rs, ps, connect);
        }
        result.setSuccess(true);
        result.setRoot(dataList);
        result.setMessage("操作成功");
        return result;
    }

    private void replaceParam(PreparedStatement ps, Param param) throws SQLException {
        //1. 查出参数定义
        Connection connect = null;
        PreparedStatement pss = null;
        ResultSet rs = null;
        try {
            connect = JDBCUtils.getConnection();
            String sql = "SELECT * FROM t_router_param WHERE router_id = ?";
            pss =connect.prepareStatement(sql);
            pss.setInt(1,param.getRouterId());
            rs = pss.executeQuery();
            int count = 0;
            String s = count +"";
            //2. 注入参数
            while(rs.next()){
                count++;
                int type = rs.getInt("param_type");
                switch(type){
                    case 1:
                        ps.setString(count, param.getData().get(count+""));
                        continue;
                    case 2:
                        ps.setInt(count, Integer.parseInt(param.getData().get(count+"")));
                        continue;
                }
            }
        }finally{
            connect.close();
        }
    }

    private int countChar(String str, char ch) {
        int count = 0;
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if(chars[i] == ch){
                count++;
            }
        }
        return count;

    }

}
